package com.example.f8399.testdemo.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.f8399.testdemo.BaseActivity;
import com.example.f8399.testdemo.R;
import com.example.f8399.testdemo.databinding.ActivityTakePhotoBinding;
import com.example.f8399.testdemo.utils.PermissionsUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author lcfeng
 * @description 拍照.
 *
 * 参考：https://developer.android.com/training/camera/photobasics
 * @date 2018/9/20 12:23.
 **/
public class TakePhotoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    ActivityTakePhotoBinding mBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_take_photo);


    }


    public void takePhoto(View view) {
        if (PermissionsUtil.hasCameraPermission(this)) {

            dispatchTakePictureIntent();
        }
    }

    public void takeBigPhoto(View view) {
        if (PermissionsUtil.hasCameraPermission(this)) {

            dispatchTakeBigPictureIntent();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMAGE_CAPTURE) {
                //显示缩略图
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                mBinding.iv.setImageBitmap(imageBitmap);
            } else if (requestCode == REQUEST_TAKE_PHOTO) {
                //显示原图
                Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
                //这个是临时使用工具类压缩了以下图片
                Bitmap compressByQuality = ImageUtils.compressByQuality(bm, 50);
                mBinding.iv.setImageBitmap(compressByQuality);

            } else if (requestCode == PermissionsUtil.REQUST_PERMISSION_CODE_CAMERA) {
                //dispatchTakePictureIntent(); //小图片
                //dispatchTakeBigPictureIntent(); // 大图片

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }


//*****************************************小图片*********以下******************************

    static final int REQUEST_IMAGE_CAPTURE = 1;

    /**
     * 获取缩略图（按需使用）
     */
    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
//*****************************************小图片*********以上******************************


//*****************************************大图片*********以下******************************
static final int REQUEST_TAKE_PHOTO = 2;

    /**
     * 获取原尺寸大图（未压缩）
     */
    private void dispatchTakeBigPictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                LogUtils.e(ex.toString());
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.f8399.testdemo.provider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = TimeUtils.getNowString(new java.text.SimpleDateFormat("yyyyMMdd_HHmmss"));
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
//*****************************************大图片********以上*******************************


}
